package com.luoying.itew.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;

import com.google.gson.Gson;
import com.luoying.itew.R;
import com.luoying.itew.bean.SubmitLogDetailsBean;
import com.luoying.itew.bean.SubmitLogPBean;
import com.luoying.itew.event.SelectLogEvent;
import com.luoying.itew.http.BaseMap;
import com.luoying.itew.http.HttpRequestUtils;
import com.luoying.itew.http.HttpResponseCallBack;
import com.luoying.itew.manage.UserManage;
import com.luoying.itew.util.LogUtils;
import com.luoying.itew.view.LogSelectItemView;
import com.luoying.itew.view.NewGridView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/5/26.
 * time 2018-5-10
 * author zm
 */
public class SubmitLogActivity extends BaseActivity {
    private static final String TAG = "SubmitLogActivity";
    public static String LOG = "log";
    public static String NEAR = "near";
    public static String ROAD = "road";
    @BindView(R.id.lr_submit_Log_base)
    LinearLayout lrSubmitLogBase;
    @BindView(R.id.gv_monitoring_log)
    NewGridView gvMonitoringLog;
    @BindView(R.id.gv_monitoring_near)
    NewGridView gvMonitoringNear;
    @BindView(R.id.gv_road_log)
    NewGridView gvRoadLog;

    @BindView(R.id.rl_submit_feedback)
    RelativeLayout rlSubmitFeedback;

    private LogAdapter logAdapter;
    private NearAdapter nearAdapter;
    private RoadAdapter roadAdapter;

    public static Activity mFinish;
    private Map<String, Boolean> logMap = new HashMap<>();
    private Map<String, Boolean> nearMap = new HashMap<>();
    private Map<String, Boolean> roadMap = new HashMap<>();
    private String address;
    //数组
    private String[] selectType1 = {
            "位移", "位移走势", "位移速度", "位移加速度"
    };
    private String[] selectType2 = {
            "位移走势", "位移速度", "位移加速度"
    };
    private String[] selectType3 = {
            "水平位移", "沉降位移"
    };
    private List<String> roadVule;
    private List<String> logValue;
    private List<String> nearValue;
    private List<String> postRoadVaule = new ArrayList<>();
    private List<String> postLogValue = new ArrayList<>();
    private List<String> postNearValue = new ArrayList<>();
    private int userId;
    private ProgressDialog dialog;

    @Override
    public int getLayoutResId() {
        return R.layout.submit_log_activity;
    }

    @Override
    protected void init() {
        super.init();
        mFinish = this;
        loadDialog.show();
        registerEventBus();
        getThings();
        sendRequest();
    }

    /**
     * 网络请求
     */
    private void sendRequest() {
        HttpRequestUtils.getInstance().getSignDetails(new HttpResponseCallBack<Map>() {
            @Override
            public void onFail(String message) {
                loadDialog.dismiss();
                LogUtils.d(TAG, "onFail == " + message);
            }

            @Override
            public void onSuccess(Map data) {
                //String response = new Gson().toJson(data);
                String response = new Gson().toJson(data);
                SubmitLogDetailsBean submitLogDetailsBean = new Gson().fromJson(response, SubmitLogDetailsBean.class);
                setData(submitLogDetailsBean);

            }

            @Override
            public void onError(String message) {
                loadDialog.dismiss();
                LogUtils.d(TAG, "onError == " + message);
            }
        });
    }

    private void setData(SubmitLogDetailsBean submitLogDetailsBean) {
        SubmitLogDetailsBean.BuildingStateBean buildingState = submitLogDetailsBean.getBuildingState();
        SubmitLogDetailsBean.MonitorStateBean monitorState = submitLogDetailsBean.getMonitorState();
        SubmitLogDetailsBean.RoadStateBean roadState = submitLogDetailsBean.getRoadState();
        logValue = monitorState.getValue();
        nearValue = buildingState.getValue();
        roadVule = roadState.getValue();
        setGirdView();
        setMap();
    }

    /**
     * 获取从上一个页面传过来的地址
     */
    private void getThings() {
        Intent intent = getIntent();
        String stringExtra = intent.getStringExtra(SignInActivity.GOING);
        if (!TextUtils.isEmpty(stringExtra)) {
            address = stringExtra;
        } else {
            address = "";
        }
        userId = UserManage.getInstance().getUserInfo().getUserId();
        LogUtils.d(TAG, "address == " + address);
    }

    /**
     * 将数据添加到map集合里
     */
    private void setMap() {
        for (int i = 0; i < logValue.size(); i++) {
            logMap.put(logValue.get(i), false);
        }
        for (int i = 0; i < nearValue.size(); i++) {
            nearMap.put(nearValue.get(i), false);
        }
        for (int i = 0; i < roadVule.size(); i++) {
            roadMap.put(roadVule.get(i), false);
        }
        loadDialog.dismiss();

    }

    /**
     * 接收itmeview传过来的数据，并添加到map集合
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(SelectLogEvent event) {

        String type = event.getType();
        String name = event.getName();
        boolean checked = event.isChecked();
        LogUtils.d(TAG, "type == " + type + ",signAddress == " + name + ",boolean == " + checked);
        if (type.equals(LOG)) {
            logMap.put(name, checked);
        } else if (type.equals(NEAR)) {
            nearMap.put(name, checked);
        } else {
            roadMap.put(name, checked);
        }

    }

    private void registerEventBus() {
        EventBus.getDefault().register(this);
    }

    private void setGirdView() {
        logAdapter = new LogAdapter(this);
        gvMonitoringLog.setAdapter(logAdapter);
        nearAdapter = new NearAdapter(this);
        gvMonitoringNear.setAdapter(nearAdapter);
        roadAdapter = new RoadAdapter(this);
        gvRoadLog.setAdapter(roadAdapter);
    }

    private int logSelect;

    class LogAdapter extends BaseAdapter {
        int mposition;
        //上下文对象
        private Context context;


        LogAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return logValue.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, final View convertView, ViewGroup parent) {
            mposition = position;

            final LogSelectItemView button;
            if (convertView == null) {

                button = new LogSelectItemView(context);

            } else {
                button = (LogSelectItemView) convertView;
            }
           /* if (logSelect == position) {
                button.setSelect();
            } else {
                button.setNormal();
            }*/
            button.setText(logValue.get(position), LOG);//为ImageView设置图片资源
            return button;

        }
    }

    private int nearSelect;

    class NearAdapter extends BaseAdapter {
        int mposition;
        //上下文对象
        private Context context;


        NearAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return nearValue.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, final View convertView, ViewGroup parent) {
            mposition = position;

            final LogSelectItemView button;
            if (convertView == null) {

                button = new LogSelectItemView(context);

            } else {
                button = (LogSelectItemView) convertView;
            }

            button.setText(nearValue.get(position), NEAR);//为ImageView设置图片资源
            return button;

        }
    }

    private int roadSelect;

    class RoadAdapter extends BaseAdapter {
        int mposition;
        //上下文对象
        private Context context;


        RoadAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return roadVule.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, final View convertView, ViewGroup parent) {
            mposition = position;

            final LogSelectItemView button;
            if (convertView == null) {

                button = new LogSelectItemView(context);

            } else {
                button = (LogSelectItemView) convertView;
            }

            button.setText(roadVule.get(position), ROAD);//为ImageView设置图片资源
            return button;

        }
    }

    @Override
    protected void setSystemColor() {
        super.setSystemColor();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //点击back键finish当前activity
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }

    @OnClick({ R.id.rl_submit_feedback,R.id.lr_submit_Log_base})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_submit_feedback:
                rlSubmitFeedback.setEnabled(false);
                loadDialog.show();
                sendPostRequest();
                break;
        }
    }

    private void sendPostRequest() {
        postNearValue.clear();
        postLogValue.clear();
        postRoadVaule.clear();
        if (logValue == null) {
            Toast.makeText(this,"没有可以提交的数据",Toast.LENGTH_SHORT).show();
            loadDialog.dismiss();
            return;
        }
        for (String key : logValue) {        //通过遍历Map集合中选中的值，添加到集合中
            Boolean aBoolean = logMap.get(key);
            if (aBoolean) {
                postLogValue.add(key);
            }
        }

        for (String key : nearValue) {
            Boolean aBoolean = nearMap.get(key);
            if (aBoolean) {
                postNearValue.add(key);
            }
        }

        for (String key : roadVule) {
            Boolean aBoolean = roadMap.get(key);
            if (aBoolean) {
                postRoadVaule.add(key);
            }
        }

        if (postLogValue.size() == 0) {
            Toast.makeText(SubmitLogActivity.this, getString(R.string.submit_log_monitoring_toast), Toast.LENGTH_SHORT).show();
            rlSubmitFeedback.setEnabled(true);
            loadDialog.dismiss();
            return;
        } else if (postNearValue.size() == 0) {
            Toast.makeText(SubmitLogActivity.this, getString(R.string.submit_log_build_toast), Toast.LENGTH_SHORT).show();
            rlSubmitFeedback.setEnabled(true);
            loadDialog.dismiss();
            return;
        } else if (postRoadVaule.size() == 0) {
            Toast.makeText(SubmitLogActivity.this, getString(R.string.submit_log_road_toast), Toast.LENGTH_SHORT).show();
            rlSubmitFeedback.setEnabled(true);
            loadDialog.dismiss();
            return;
        }
        if (postLogValue.size() > 1 && postLogValue.contains("已巡查未发现异常")) {
            Toast.makeText(SubmitLogActivity.this, "监测物状态已选择 已巡查未发现异常 ，无法选择其他状态", Toast.LENGTH_SHORT).show();
            rlSubmitFeedback.setEnabled(true);
            loadDialog.dismiss();
            return;
        } else if (postNearValue.size() > 1 && postNearValue.contains("已巡查未发现异常")) {
            Toast.makeText(SubmitLogActivity.this, "周边建筑物状态已选择 已巡查未发现异常 ，无法选择其他状态", Toast.LENGTH_SHORT).show();
            rlSubmitFeedback.setEnabled(true);
            loadDialog.dismiss();
            return;
        }
        if (postRoadVaule.size() > 1 && postRoadVaule.contains("已巡查未发现异常")) {
            Toast.makeText(SubmitLogActivity.this, "周边道路状态已选择 已巡查未发现异常 ，无法选择其他状态", Toast.LENGTH_SHORT).show();
            rlSubmitFeedback.setEnabled(true);
            loadDialog.dismiss();
            return;
        }

        SubmitLogPBean.MonitorStateBean monitorStateBean = new SubmitLogPBean.MonitorStateBean("检测物状态", postLogValue);
        SubmitLogPBean.BuildingStateBean buildingStateBean = new SubmitLogPBean.BuildingStateBean("周边建筑物状态", postNearValue);
        SubmitLogPBean.RoadStateBean roadStateBean = new SubmitLogPBean.RoadStateBean("周边道路状态", postRoadVaule);

        SubmitLogPBean bean = new SubmitLogPBean("", address, roadStateBean, buildingStateBean, monitorStateBean);
        //增加校验信息
        bean.setAccess_token(String.valueOf(new BaseMap().get(BaseMap.TOKEN)));
        bean.setSign(String.valueOf(new BaseMap().get(BaseMap.SIGN)));

        goSubmitImage(bean);
    }

    /**
     * 去提交图片界面
     */
    private void goSubmitImage(SubmitLogPBean bean){
        loadDialog.dismiss();
        Intent intent = new Intent(this,SubmitPhotoActivity.class);
        intent.putExtra("bean",bean);
        startActivity(intent);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mFinish = null;
        EventBus.getDefault().unregister(this);
    }
}
